//
//  UserDefaults.swift
//  BaoDan
//
//  Created by 郭子龙 on 2025/4/3.
//

import BDKit
import Foundation

extension UserDefaults {

  /// AppGroup 共享 UserDefaults
    static let baoDan = UserDefaults(suiteName: BaoDanConstants.appGroupIdentifier)!

  // 序列化 UserData 为 JSON 字符串
  func saveUserDataToUserDefaults(userData: UserData) {
    let encoder = JSONEncoder()
    encoder.dateEncodingStrategy = .iso8601  // 可根据需要调整日期格式

    do {
      let data = try encoder.encode(userData)
      if let jsonString = String(data: data, encoding: .utf8) {
        // 存储到 UserDefaults（或者存储到 App Group 共享 UserDefaults）
        let sharedDefaults = UserDefaults(suiteName: BaoDanConstants.appGroupIdentifier)
        sharedDefaults?.set(jsonString, forKey: UserDefaults.userDataKey)
        sharedDefaults?.synchronize()
      }
    } catch {
      print("Error encoding user data: \(error)")
    }
  }

  // 从 UserDefaults 中读取并解码 JSON 字符串为 UserData
  func loadUserDataFromUserDefaults() -> UserData? {
    let sharedDefaults = UserDefaults(suiteName: BaoDanConstants.appGroupIdentifier)

    if let jsonString = sharedDefaults?.string(forKey: UserDefaults.userDataKey),
      let data = jsonString.data(using: .utf8)
    {
      let decoder = JSONDecoder()
      do {
        let userData = try decoder.decode(UserData.self, from: data)
        return userData
      } catch {
        print("Error decoding user data: \(error)")
        return nil
      }
    }
    return nil
  }

  // 清空本地缓存
  func removeUserDataFromUserdefaults() {
    let sharedDefaults = UserDefaults(suiteName: BaoDanConstants.appGroupIdentifier)
    sharedDefaults?.removeObject(forKey: UserDefaults.userDataKey)
    sharedDefaults?.removeObject(forKey: UserDefaults.tokenKey)
  }
}

// Keys
//extension UserDefaults {
//    static let tokenKey = "userToken"
//    static let userNameKey = "userName"
//    static let userDataKey = "userData"
//
//    static let taskIdKey = "taskId"
//}
